<style lang="scss">
  page{
    height: 100vh;
    overflow-y: hidden;
  }
  .intro {
    margin: 30px;
    text-align: center;
  }

  .camera{
    /*position: fixed;*/
    /*top: 0;*/
    /*z-index: 2;*/
    width: 750rpx;
  }

  .webgl{
    /* position: absolute;
    top: 0;
    left:0;
    width: 750rpx; */
  }

  .cameraTempPath{
    width: 750rpx;
    position: fixed;
    z-index: 3;
    top:0;
    vertical-align: top;
    margin: 0;
    padding: 0;
  }

  .base{
    width: 750rpx;
    position: fixed;
    z-index: 3;
    bottom: 92rpx;
    vertical-align: top;
    margin: 0;
    padding: 0;
  }

  .btn-wrap{
    position: fixed;
    width: 750rpx;
    height: 92rpx;
    overflow: hidden;
    z-index: 4;
    bottom: 0;

  }
  .btn{
    height: 92rpx;
    border-radius: 0;
  }

</style>
<template>

  <div class="page-wrap">
    <camera
        device-position="back"
        flash="off"
        :style="{height:height+'px'}"
        binderror="error"
        class="camera"
        frame-size="large"
    ></camera>

    <cover-image :style="{height:height+'px'}" v-if="!show" mode="aspectFill" class="cameraTempPath" :src="cameraTempPath"></cover-image>

    <cover-image :style="{height:baseH+'px'}" mode="aspectFill" class="base" :src="vo.thumb"></cover-image>

    <cover-view class="btn-wrap">
      <button :disabled="is_click" class="btn" @click="creat"  type="primary">拍照分享</button>
    </cover-view>

    <canvas class="myCanvas" canvas-id="webgl2" id="webgl2" :style="{width: width*info.pixelRatio+'rpx',height: canvasH+'rpx'}"></canvas>

  </div>

</template>
<script>
import { pageMixin } from '@/mixins'
import { getPosterPic, poster } from '@/api'
import { downLoadFile, setNavigationBarTitle, uploadImages } from '@/common/helper'
import { error, hideLoading, showLoading, toast } from '@/common/fun'
import Promisify from '@/common/Promisify'
import { Exception } from '@/common/Exception'

var wrapCTX = null
var contextCTX = null
export default {
  mixins: [pageMixin],
  data () {
    return {
      is_click: false,
      cameraTempPath: false,
      vo: {},
      width: 0,
      height: 0,
      baseH: 0,
      canvasH: 0,
      shareImg: null,
      show: true,
      info: null
    }
  },
  methods: {
    previewImage () {
      var tempFilePath = this.shareImg
      wx.previewImage({
        current: tempFilePath, // 当前显示图片的http链接
        urls: [tempFilePath] // 需要预览的图片http链接列表
      })
    },
    takePhotoFn () {
      return new Promise((resolve, reject) => {
        contextCTX.takePhoto({
          quality: 'high',
          fail: () => {
            reject(Error('拍照失败'))
          },
          success: (res) => {
            console.log(res.tempImagePath)
            resolve(res.tempImagePath)
          }
        })
      })
    },
    async creat () {
      try {
        this.is_click = true

        var ctx = wrapCTX
        showLoading('操作中')

        const cameraTempPath = await this.takePhotoFn().catch(err => {
          throw err
        })

        this.show = false
        this.cameraTempPath = cameraTempPath

        ctx.drawImage(cameraTempPath, 0, 0, this.info.windowWidth, this.height)

        const canvasImgUrl = await downLoadFile(this.vo.thumb).catch(err => {
          throw Error('下载图片失败')
        })

        console.log('canvasImgUrl', canvasImgUrl)
        ctx.drawImage(canvasImgUrl, 0, this.height, this.info.windowWidth, this.baseH)

        await new Promise(resolve => {
          ctx.draw(false, function () {
            console.log('draw done')
            resolve()
          })
        })

        const toFileConf = {
          x: 0,
          y: 0,
          width: this.info.windowWidth,
          heigh: this.canvasH,
          // destWidth:_self.info.windowWidth,
          // destHeight:outputH,
          fileType: 'jpg',
          canvasId: 'webgl2'
        }
        var { tempFilePath: shareImg } = await Promisify('canvasToTempFilePath', { ...toFileConf }).catch(err => {
          console.log(err)
          throw Error(err.errMsg || '合成图片失败')
        })
        console.log('shareImg', shareImg)

        this.shareImg = shareImg
        this.is_click = false
        this.show = true

        uni.previewImage({
          current: shareImg, // 当前显示图片的http链接
          urls: [shareImg] // 需要预览的图片http链接列表
        })

        const uploadRet = uploadImages({ imgs: [shareImg] }).then(res => {
          return res.data
        }).catch(err => {
          throw Error('上传拼接好的图片失败')
        })

        await getPosterPic({ poster_id: this.vo.id, pic: uploadRet }).catch(() => {
          throw Error('保存图片到海报合集失败')
        })

        hideLoading()
        this.is_click = false
      } catch (e) {
        console.log(e)
        hideLoading()
        this.is_click = false
        e.type = 'modal'
        Exception.handle(e)
      }
    },
    async _init_func () {
      poster({ id: this.id }).then(res => {
        const ret = res.data
        this.vo = ret
        setNavigationBarTitle(ret.title)
      })
    }
  },
  onReady () {
    const content = uni.createCameraContext()
    const wrap = uni.createCanvasContext('webgl2', this)
    const info = uni.getSystemInfoSync()

    contextCTX = content
    this.info = info
    wrapCTX = wrap

    this.width = info.windowWidth
    this.height = info.windowHeight - parseInt(info.windowWidth / 658 * 372)// 去掉底部照片

    this.baseH = parseInt(info.windowWidth / 658 * 372)
    this.canvasH = info.windowHeight
  },

  onLoad (options) {
    this.id = options.id
    this._init_func()
  },

  onShareAppMessage () {
  // let userInfo = wx.getStorageSync('userInfo'),path = '/pages/map/deatil?id='+this.map.id;
    //
    // //加入分享标识
    // if(userInfo && userInfo.id){
    //   path = path + '&from_mid=' + userInfo.id
    // }
    //
    return {
      title: '自定义海报'
    // imageUrl: this.map.thumb || wx.state.logo,
    // path: path
    }
  }

}
</script>
